package cn.school.mybatis.filter;

import cn.school.mybatis.pojo.Admin;
import cn.school.mybatis.service.AdminService;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/login.jsp")
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//        HttpServletRequest request = (HttpServletRequest) req;
//        HttpServletResponse response = (HttpServletResponse) resp;
//        String username = (String) request.getSession().getAttribute("username");//获取Session的值
//        String password = null;
//        if (username == null) {//如果未登录，获取客户端Cookie，并登录
//            Cookie[] cookies = request.getCookies();
//            if (cookies != null) {//获取客户端Cookie
//                for (Cookie c : cookies) {
//                    if (c.getName().equals("username")) {
//                        username = c.getValue();
//                    }
//                    if (c.getName().equals("password")) {
//                        password = c.getValue();
//                    }
//                }
//            }
//            if (username != null && password != null) {//如何账号密码获取成功，则进行登录
//                //判断账号密码是否正确
//                Admin checkAdmin = AdminService.ADMIN_SERVICE.getUser(username, password);
//                if (checkAdmin != null) {
//                    //登录成功刷新客户端Cookie
//                    Cookie c1 = new Cookie("username", username);
//                    Cookie c2 = new Cookie("password", password);
//                    c1.setMaxAge(60 * 60 * 24 * 30);
//                    c2.setMaxAge(60 * 60 * 24 * 30);
//                    response.addCookie(c1);
//                    response.addCookie(c2);
//                    request.getSession().setAttribute("username", username);
//                }
//            }
//        }
        chain.doFilter(req, resp);

    }

    public void init(FilterConfig config) throws ServletException {

    }

}
